package translate

import (
	"fmt"
	"github.com/name5566/leaf/gate"
	"github.com/name5566/leaf/log"
	"go.mongodb.org/mongo-driver/bson"
	"server/cfg"
	db2 "server/db"
	"server/game/activity"
	"server/game/bag"
	db3 "server/game/bag/db"
	"server/game/card"
	"server/game/item"
	"server/game/level"
	"server/game/translate/db"
	"server/msg/jsonData"
	"server/util"
	"strconv"
	"strings"
	"time"
)

/*
*
获取收益
*/
func GetTranslateShouYi(uid string) (map[string]interface{}, error) {
	var ret = make(map[string]interface{}, 0)
	num := GetChangYeChaoPiaoNum(uid)
	bagList, err := bag.EnAddItem(uid, db3.Chaopiao, int(num))
	if err != nil {
		return ret, err
	}
	db2.Db.Update(db.TranslateInfoCollectName, bson.M{"user_id": uid}, map[string]interface{}{
		"$set": map[string]interface{}{"shou_yi_ctime": time.Now().Unix()},
	})
	ret["bag_list"] = bagList
	ret["add_num"] = num
	return ret, nil
}

func CreateTranslateInfo(userId string, tid int64) ([]TranslateInfoDb, error) {
	Tid, err := util.IdGen()
	if err != nil {
		return nil, fmt.Errorf("系统错误")
	}
	var translateCheck TranslateInfoDb
	err = db2.Db.FindOne(db.TranslateInfoCollectName, bson.M{"TT_Id": tid, "user_id": userId}, &translateCheck)
	if err == nil && translateCheck.TT_id == tid {
		return nil, fmt.Errorf("请不要重复解锁产业")
	}
	var translateInfo = TranslateInfoDb{
		UserId:      userId,
		T_id:        Tid,
		TT_id:       tid,
		Level:       1,
		ExpandLevel: 1,
		CardTooles:  make([]CardToole, 0),
		Ids:         make([]int, 0),
	}
	config := cfg.ConfigData.TbBuildBase.Get(int32(tid))
	if config.DaSaoCiShu != -1 {
		translateInfo.DaoSaoCiShu = 0
	} else {
		translateInfo.DaoSaoCiShu = int(config.DaSaoCiShu)
	}
	err = db2.Db.Insert(db.TranslateInfoCollectName, translateInfo)
	if err != nil {
		return nil, err
	}
	translateInfoList := translateList(userId)

	return translateInfoList, nil
}
func TranslateList(args []interface{}) {
	m := args[0].(*jsonData.MsgTranslateListReq)
	// 消息的发送者
	a := args[1].(gate.Agent)
	translateInfoList := translateList(m.UserId)

	a.WriteMsg(&jsonData.MsgRes{Ret: 0, Result: translateInfoList, RequestId: m.RequestId})
}
func translateList(userId string) []TranslateInfoDb {
	var translateInfoList []TranslateInfoDb
	err := db2.Db.Find(db.TranslateInfoCollectName, bson.M{"user_id": userId}, &translateInfoList)
	if err != nil {
		log.Error("获取关卡列表错误信息%s", err.Error())
	}
	return translateInfoList
}

func UnlocksCareer(userId string, TTid, cid int) (TranslateInfoDb, error) {
	var translateInfo TranslateInfoDb
	err := db2.Db.FindOne(db.TranslateInfoCollectName, bson.M{"user_id": userId, "TT_Id": TTid}, &translateInfo)
	if err != nil {
		return translateInfo, err
	}
	check := util.Contains(translateInfo.Ids, cid)
	if check {
		return translateInfo, fmt.Errorf("不能重复解锁")
	}
	translateInfo.Ids = append(translateInfo.Ids, cid)
	err = db2.Db.Update(db.TranslateInfoCollectName, bson.M{"user_id": userId, "TT_Id": TTid}, map[string]interface{}{
		"$set": map[string]interface{}{"ids": translateInfo.Ids},
	})
	if err != nil {
		return translateInfo, fmt.Errorf("修改数据失败")
	}
	_, err = CreateUserBreakfast(userId, cid)
	return translateInfo, nil
}
func UnLockNpc(translateInfo TranslateInfoDb) (TranslateInfoDb, error) {
	customerConfigList := cfg.ConfigData.TbCustomer.GetDataList()
	for _, customerConfig := range customerConfigList {
		if customerConfig.GetWay != "0" {
			npcs := strings.Split(customerConfig.GetWay, "_")
			npcTid, _ := strconv.ParseInt(npcs[0], 10, 64)
			unLock, _ := strconv.ParseInt(npcs[1], 10, 64)
			if translateInfo.TT_id == npcTid && translateInfo.Level >= unLock {
				if _, ok := translateInfo.Npcs[customerConfig.Id]; !ok {
					translateInfo.Npcs[customerConfig.Id] = NPC{
						Name:     customerConfig.Name,
						IsReward: false,
					}
				}
			}
		}
	}
	return translateInfo, nil
}
func UpdateTranslateLevel(userId string, Tid, step int64) (map[string]interface{}, error) {
	var ret = make(map[string]interface{}, 0)
	var translateInfo TranslateInfoDb
	err := db2.Db.FindOne(db.TranslateInfoCollectName, bson.M{"TT_Id": Tid, "user_id": userId}, &translateInfo)
	if err != nil {
		return ret, err
	}
	var costChaoPiao int
	dengJiConfig := cfg.ConfigData.TbBuildLevel.Get(int32(translateInfo.Level + step))
	jianZhuConfig := cfg.ConfigData.TbBuildBase.Get(int32(translateInfo.TT_id))
	switch jianZhuConfig.Id {
	case 1:
		costChaoPiao = int(dengJiConfig.Money1)
		break
	case 2:
		costChaoPiao = int(dengJiConfig.Money2)
		break
	case 3:
		costChaoPiao = int(dengJiConfig.Money3)
		break
	case 4:
		costChaoPiao = int(dengJiConfig.Money4)
		break
	case 5:
		costChaoPiao = int(dengJiConfig.Money5)
		break
	case 6:
		costChaoPiao = int(dengJiConfig.Money6)
		break
	case 7:
		costChaoPiao = int(dengJiConfig.Money7)
		break
	case 8:
		costChaoPiao = int(dengJiConfig.Money8)
		break
	case 9:
		costChaoPiao = int(dengJiConfig.Money9)
		break
	case 10:
		costChaoPiao = int(dengJiConfig.Money10)
		break
	}
	bagList, err := bag.EnUseItem(userId, db3.Chaopiao, costChaoPiao)
	if err != nil {
		return ret, err
	}
	translateInfo.Level += step
	translateInfo, _ = UnLockNpc(translateInfo)
	err = db2.Db.Update(db.TranslateInfoCollectName,
		map[string]interface{}{"TT_Id": Tid, "user_id": userId},
		map[string]interface{}{"$set": map[string]interface{}{"level": translateInfo.Level, "npcs": translateInfo.Npcs}})
	if err != nil {
		log.Error("更新产业文档失败 %v", err)
		return ret, err
	}
	unLockIds, yeWuList := unLockChanYe(userId, int(Tid), &translateInfo, 0)
	translateInfoList := translateList(userId)
	ret["un_lock_ids"] = unLockIds
	ret["un_lock"] = yeWuList
	ret["translate_list"] = translateInfoList
	ret["bag_list"] = bagList
	return ret, nil
}
func UpdateTranslateExpandLevel(userId string, tid, step int64) (map[string]interface{}, error) {

	var translateInfo TranslateInfoDb
	var ret = make(map[string]interface{}, 0)
	err := db2.Db.FindOne(db.TranslateInfoCollectName, bson.M{"TT_Id": tid, "user_id": userId}, &translateInfo)
	if err != nil {
		return ret, err
	}
	translateInfo.ExpandLevel += step
	var bagList []item.Item
	buildExpandConfigList := cfg.ConfigData.TbBuildExpand.GetDataList()
	for _, buildExpandConfig := range buildExpandConfigList {
		if buildExpandConfig.Expand == int32(tid) && buildExpandConfig.Expandlv == int32(translateInfo.ExpandLevel) {
			if buildExpandConfig.UnlockBusiness != 0 {
				parts := strings.Split(buildExpandConfig.Num, "_")
				itemId, _ := strconv.Atoi(parts[0])
				num, _ := strconv.Atoi(parts[1])
				bagList, err = bag.EnUseItem(userId, itemId, num)
				if err != nil {
					return ret, fmt.Errorf("物品不能使用")
				}
				CreateUserBreakfast(userId, int(buildExpandConfig.UnlockBusiness))
			}
			translateInfo.MaxLevel = buildExpandConfig.LvLimit
		}
	}
	db2.Db.Update(db.TranslateInfoCollectName,
		bson.M{"TT_Id": tid, "user_id": userId},
		map[string]interface{}{"$set": map[string]interface{}{"expand_level": translateInfo.ExpandLevel, "max_level": translateInfo.MaxLevel}})
	translateInfoList := translateList(userId)
	breakFastList, _ := GetBreakfastList(userId)
	ret["translate_list"] = translateInfoList
	ret["breakfast_list"] = breakFastList
	ret["bag_list"] = bagList
	return ret, nil
}

//func DoIt(args []interface{}) {
//	m := args[0].(*jsonData.MsgTranslateProductReq)
//	// 消息的发送者
//	a := args[1].(gate.Agent)
//	var err error
//	switch m.TranslateType {
//	case 1:
//		breakFast, err := GetBreakfast(m.UserId, m.Cid)
//		if err != nil {
//			a.WriteMsg(&jsonData.MsgRes{Ret: 1, Message: err.Error()})
//			return
//		}
//		err = breakFast.ProduceBreakfast(m.ArgsValue)
//		if err != nil {
//			a.WriteMsg(&jsonData.MsgRes{Ret: 1, Message: err.Error()})
//			return
//		}
//		a.WriteMsg(&jsonData.MsgRes{Ret: 0})
//		break
//
//	}
//	if err != nil {
//		code := jsonData.ErrCode(2)
//		a.WriteMsg(&jsonData.MsgRes{Ret: code})
//	}
//	a.WriteMsg(&jsonData.MsgRes{
//		Ret: jsonData.ErrCode(0),
//	})
//}

/*
*
获取赚速
*/
func GetChangYeChaoPiaoNum(uid string) float32 {
	var chaoPiaoShu float32 = 0
	translateInfoList := translateList(uid)

	for _, translateInfo := range translateInfoList {
		diffTime := time.Now().Unix() - translateInfo.ShouYiCtime
		chaoPiaoShu += GetEarnSpeed(uid, translateInfo) * float32(diffTime)
	}

	return chaoPiaoShu
}
func GetEarnSpeed(uid string, translateInfo TranslateInfoDb) float32 {
	var earnBase float32 = 0
	var yinShiZuoPinZongShouRu float32
	var qiTaJiaCheng float32
	yueKaJiaCheng := activity.GetYueKaJiaCheng(uid)
	nianKaJiaCheng := activity.GetNianKaJiaCheng(uid)
	guanKaJianCheng := level.EnGetLevelJiaCheng(uid)
	guanKaiPeiXunShouRu := level.EnGetLevelPeiXunShouRu(uid)
	earnBase = (float32(cfg.ConfigData.TbBuildBase.Get(int32(translateInfo.TT_id)).Earn*int32(translateInfo.Level)) + (card.EnGetUserAllCardNengLi(uid) / 1000)) * (1 + qiTaJiaCheng)
	dianPuShouRu := (earnBase + guanKaiPeiXunShouRu + yinShiZuoPinZongShouRu) * (1 + yueKaJiaCheng + nianKaJiaCheng + guanKaJianCheng)
	return dianPuShouRu
}
func DaSao(uid string, t_id int64) (map[string]interface{}, error) {
	var translateInfo TranslateInfoDb
	var ret = make(map[string]interface{}, 0)
	err := db2.Db.FindOne(db.TranslateInfoCollectName, bson.M{"user_id": uid, "TT_Id": t_id}, &translateInfo)
	if err != nil {
		return ret, err
	}
	config := cfg.ConfigData.TbBuildBase.Get(int32(t_id))
	if translateInfo.DaoSaoCiShu >= int(config.DaSaoCiShu+1) {
		return ret, fmt.Errorf("不能打扫了")
	}
	bagList, err := bag.EnAddItem(uid, db3.Zuanshi, 10)
	ret["bag_list"] = bagList
	if translateInfo.DaoSaoCiShu <= 0 {
		translateInfo.DaoSaoCiShu = 0
	}
	translateInfo.DaoSaoCiShu = translateInfo.DaoSaoCiShu + 1
	if config.DaSaoCiShu <= int32(translateInfo.DaoSaoCiShu) {
		ret["is_kaiye"] = true
	} else {
		ret["is_kaiye"] = false
	}
	err = db2.Db.Update(db.TranslateInfoCollectName,
		bson.M{"user_id": uid, "TT_Id": t_id},
		map[string]interface{}{"$set": map[string]interface{}{"dao_sao_ci_shu": translateInfo.DaoSaoCiShu}})
	ret["translate_info"] = translateInfo
	return ret, nil
}
func UnlockCardTool(userId string, tid, cardIndex int) (map[string]interface{}, error) {
	var translateCheck TranslateInfoDb
	var ret = make(map[string]interface{}, 0)
	err := db2.Db.FindOne(db.TranslateInfoCollectName, bson.M{"T_Id": tid, "user_id": userId}, &translateCheck)
	if err != nil {
		return ret, err
	}
	if len(translateCheck.CardTooles) > cardIndex {
		return ret, fmt.Errorf("超过长度")
	}
	translateCheck.CardTooles = append(translateCheck.CardTooles, CardToole{})
	db2.Db.Update(BreakfastTableName, bson.M{"uid": userId, "T_Id": tid}, map[string]interface{}{
		"$set": map[string]interface{}{"card_tooles": translateCheck.CardTooles},
	})
	return ret, nil
}
func PushCardTool(userId, cardId string, Tid, cardIndex, jobType int) (map[string]interface{}, error) {
	var translateCheck TranslateInfoDb
	var ret = make(map[string]interface{}, 0)
	err := db2.Db.FindOne(db.TranslateInfoCollectName, bson.M{"T_Id": Tid, "user_id": userId}, &translateCheck)
	if err != nil {
		return ret, fmt.Errorf("没有找到数据")
	}
	if len(translateCheck.CardTooles) < cardIndex {
		return ret, fmt.Errorf("超过长度")
	}
	translateCheck.CardTooles[cardIndex].CardId = cardId
	translateCheck.CardTooles[cardIndex].StarTime = time.Now().Unix()
	translateCheck.CardTooles[cardIndex].JobType = jobType
	db2.Db.Update(BreakfastTableName,
		bson.M{"uid": userId, "T_Id": Tid},
		map[string]interface{}{
			"$set": map[string]interface{}{"card_tooles": translateCheck.CardTooles},
		})
	ret["translate_info"] = translateCheck
	return ret, nil
}
func KaiYe(userId string, Tid int) (map[string]interface{}, error) {
	var ret = make(map[string]interface{}, 0)
	var translateCheck TranslateInfoDb
	err := db2.Db.FindOne(db.TranslateInfoCollectName, bson.M{"TT_Id": Tid, "user_id": userId}, &translateCheck)
	if err != nil || translateCheck.DaoSaoCiShu == 9999 {
		return ret, fmt.Errorf("还不能开业，或者已经开业了")
	}
	config := cfg.ConfigData.TbBuildBase.Get(int32(translateCheck.TT_id))
	if translateCheck.DaoSaoCiShu < int(config.DaSaoCiShu) {
		return ret, fmt.Errorf("次数不够")
	}
	translateCheck.DaoSaoCiShu = 9999
	unLockIds, yeWuList := unLockChanYe(userId, Tid, &translateCheck, 1)
	translateCheck, _ = UnLockNpc(translateCheck)
	err = db2.Db.Update(db.TranslateInfoCollectName,
		bson.M{"TT_Id": Tid, "user_id": userId},
		map[string]interface{}{
			"$set": map[string]interface{}{"dao_sao_ci_shu": translateCheck.DaoSaoCiShu, "npcs": translateCheck.Npcs},
		})
	if err != nil {
		log.Error("update translateCheck is %s", err.Error())
	}
	ret["translate_info"] = translateCheck
	ret["un_lock_ids"] = unLockIds
	ret["un_lock"] = yeWuList
	return ret, nil
}
func unLockChanYe(userId string, tid int, translateInfo *TranslateInfoDb, isBegin int32) ([]int32, []PlayerBreakfast) {
	unLockIds := []int32{}
	yeWuConfigList := cfg.ConfigData.TbBuildBusiness.GetDataList()
	for _, yeWuConfig := range yeWuConfigList {
		if yeWuConfig.BaseType == int32(tid) && int64(yeWuConfig.UnlockBusiness) == translateInfo.Level && yeWuConfig.BusinessType == 1 && yeWuConfig.IsBeginUnlock == isBegin {
			if !util.Contains(unLockIds, yeWuConfig.Id) {
				unLockIds = append(unLockIds, yeWuConfig.Id)
			}

		}
		if yeWuConfig.BusinessType == 2 {
			buildExpandList := cfg.ConfigData.TbBuildExpand.GetDataList()
			for _, buildExpand := range buildExpandList {
				if buildExpand.Expand == int32(tid) {
					if buildExpand.Expandlv == int32(translateInfo.ExpandLevel) {
						if !util.Contains(unLockIds, buildExpand.UnlockBusiness) {
							log.Debug("expandlv Is %d, tid is %d, uid is %d expandis Is %d",
								buildExpand.Expandlv,
								tid,
								yeWuConfig.Id, buildExpand.Expand)
							unLockIds = append(unLockIds, buildExpand.UnlockBusiness)
						}
					}
				}
			}
		}
	}
	var yeWuList []PlayerBreakfast
	for _, id := range unLockIds {
		yeWu, err := CreateUserBreakfast(userId, int(id))
		if err == nil {
			yeWuList = append(yeWuList, *yeWu)
		} else {
			log.Error("CreateUserBreakfast is wrong msg is %v", err)
		}
	}
	return unLockIds, yeWuList
}
func Reward(userId string, t_id int64, npcId int32) (map[string]interface{}, error) {
	var ret = make(map[string]interface{}, 0)
	var translateInfo TranslateInfoDb
	err := db2.Db.FindOne(db.TranslateInfoCollectName, bson.M{"TT_Id": t_id, "user_id": userId}, &translateInfo)
	if err != nil {
		return ret, err
	}
	npcInfo := translateInfo.Npcs[npcId]
	if npcInfo.IsReward {
		return nil, fmt.Errorf("不要重复领取")
	}
	config := cfg.ConfigData.TbCustomer.Get(npcId)
	itemListConfig := strings.Split(config.UnlockReward, "|")
	if len(itemListConfig) < 2 {
		return nil, fmt.Errorf("配置文件错误")
	}
	itemOneInfoConfig := strings.Split(itemListConfig[0], "_")
	itemTwoInfoConfig := strings.Split(itemListConfig[1], "_")
	itemOneId, _ := strconv.Atoi(itemOneInfoConfig[0])
	itemOneNum, _ := strconv.Atoi(itemOneInfoConfig[1])
	itemTwoId, _ := strconv.Atoi(itemTwoInfoConfig[0])
	itemTwoNum, _ := strconv.Atoi(itemTwoInfoConfig[1])
	_, err = bag.EnAddItem(userId, itemOneId, itemOneNum)
	if err != nil {
		log.Error("用户 %s 添加物品失败 物品ID是%d 数量是%d", userId, itemOneId, itemOneNum)
	}
	bagList, err := bag.EnAddItem(userId, itemTwoId, itemTwoNum)
	if err != nil {
		log.Error("用户 %s 添加物品失败 物品ID是%d 数量是%d", userId, itemTwoId, itemTwoNum)
	}
	npcInfo.IsReward = true
	translateInfo.Npcs[npcId] = npcInfo
	err = db2.Db.Update(db.TranslateInfoCollectName,
		bson.M{"TT_Id": translateInfo.TT_id, "user_id": userId},
		map[string]interface{}{
			"$set": map[string]interface{}{"npcs": translateInfo.Npcs},
		})
	ret["bag_list"] = bagList
	ret["translate_info"] = translateInfo
	return ret, nil
}
